import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { message } from 'antd';
import {
  queryOrders,
  createProduct,
  updateProduct,
  getProduct,
  deleteProduct,
  queryProducts,
  queryPrivateCustomersList,
  queryBuyersList,
  querySupplygoodList,
  queryDrawersList,
  getBusinessParamsByCode,
  getAllCurrencys,
  getAllPorts,
  addRule,
  removeRule,
  updateRule,
  copyProduct,
} from './service';
import { TableListData } from './data.d';
import Constants from '../productManagement/utils/Constants';
const R = require('ramda');
const productAddTempIdPrefix = 'productAddTempIdPrefix_';
export interface StateType {
  data: TableListData;
}

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: StateType) => T) => T },
) => void;

export interface ModelType {
  namespace: string;
  state: {
    list: [],
    pagination: {},
    productList: {}, //产品列表
    productPage: {}, //产品列表分页
    currencys: [], // 币种列表
    StateType,
  },
  effects: {
    fetch: Effect;
    add: Effect;
    remove: Effect;
    update: Effect;
  };
  reducers: {
    save: Reducer<StateType>;
  };
}

const Model: ModelType = {
  namespace: 'productManagement',

  state: {
    list: [],
    pagination: {},
    productList: {}, //产品列表
    productPage: {}, //产品列表分页
    currencys: [], // 币种列表

  },

  effects: {

    *copyProduct({payload, callback}, { call , put}) {
      const response = yield call(copyProduct, payload);
      yield put({
        type: 'save',
        payload: response,
      });
    },

    *fetch({ payload }, { call, put }) {
      payload.type = 1;
      const response = yield call(queryProducts, payload);
      if (response.resultCode === 'ok') {
        if (!R.isEmpty(response.content) && !R.isNil(response.content)) {
          const { page, list } = response.content;
          yield put({
            type: 'refreshState',
            payload: {
              list,
              pagination: { current: page.page, total: page.totalRow, pageSize: page.size },
            },
          });
        } else {
          let page = Constants.DEFAULT_PAGE;
          yield put({
            type: 'refreshState',
            payload: {
              list: [],
              pagination: { current: page.page, total: page.totalRow, pageSize: page.size },
            },
          });
        }
      }
    },

    /**
     * 新增产品
     * @param payload
     * @param call
     * @param put
     * @param select
     */
    *createProduct({ payload }, { call, put, select }) {
      const dataSource = payload.dataSource;
      let orderProductDetails = [];
      R.map(
        product => {
          let temp = R.omit([
            'key',
            'createtime',
            'creator',
            'status',
            'updater',
            'updatetime',
            'productbranchname',
          ])(product);
          if (R.contains(productAddTempIdPrefix)(temp.id)) {
            temp.id = ''; //去掉新增临时定义的id
          }
          orderProductDetails = R.concat(orderProductDetails, [temp]);
        },
        R.isNil(dataSource.orderProductDetails) ? [] : dataSource.orderProductDetails,
      );
      dataSource.orderProductDetails = orderProductDetails;

      const response = yield call(createProduct, { ...dataSource });
      if (response.resultCode === 'ok') {
        message.info('产品创建成功！');
        if (payload.onSuccess) payload.onSuccess();
      } else {
        message.error(response.errMessage);
        if (payload.onFail) payload.onFail();
      }
    },

    /**
     * 更新产品
     * @param payload
     * @param call
     * @param put
     * @param select
     */
    *updateProduct({ payload }, { call, put, select }) {
      const dataSource = payload.dataSource;
      // const response = yield call(updateProduct, { ...dataSource });
      const response = yield call(updateProduct, { ...R.omit(['onSuccess', 'onFail'])(dataSource) });
      if (response.resultCode === 'ok') {
        message.info('产品修改成功！');
        if (payload.onSuccess) payload.onSuccess();
      } else {
        message.error(response.errMessage);
        if (payload.onFail) payload.onFail();
      }
    },

    /**
     * 根据id获取产品详情
     * @param payload
     * @param call
     * @param put
     * @param select
     */
    *getProduct({ payload }, { call, put, select }) {
      const response = yield call(getProduct, { id: payload.id });
      if (response.resultCode === 'ok') {
        yield put({
          type: 'refreshState',
          payload: {
            productList: response.content,
          },
        });
      } else {
        message.error(response.errMessage);
      }
    },

    /**
     * 根据id删除产品
     *
     * @param id
     * @returns {Promise.<void>}
     */
    *deleteProduct({ payload, callback }, { call, put }) {
      const response = yield call(deleteProduct, { id: payload.id });
      if (response.resultCode === 'ok') {
        message.info('删除报关资料成功!');
        if (callback) callback();
      }
    },

    /**
     * 查询个人客户
     *
     * @param call
     * @param put
     */
    *queryPrivateCustomersList({ payload }, { call, put }) {
      const response = yield call(queryPrivateCustomersList, { ...payload });
      if (response.resultCode === 'ok') {
        yield put({
          type: 'refreshState',
          payload: {
            privateCstList: response.content.list,
          },
        });
      } else {
        yield put({ type: 'refreshState', payload: { privateCstList: [] } });
      }
    },

    /**
     * 查询境外买家
     *
     * @param call
     * @param put
     */
    *queryBuyersList({ payload }, { call, put }) {
      const response = yield call(queryBuyersList, { ...payload });
      if (response.resultCode === 'ok') {
        yield put({
          type: 'refreshState',
          payload: {
            buyerList: response.content,
          },
        });
      } else {
        yield put({ type: 'refreshState', payload: { buyerList: [] } });
      }
    },

    /**
     * 查询境内货源地
     *
     * @param call
     * @param put
     */
    *querySupplygoodList({ payload }, { call, put }) {
      const response = yield call(querySupplygoodList, { ...payload });
      if (response.resultCode === 'ok') {
        yield put({
          type: 'refreshState',
          payload: {
            supplygoodList: response.content,
          },
        });
      } else {
        yield put({ type: 'refreshState', payload: { supplygoodList: [] } });
      }
    },

    /**
     * 查询开票人
     *
     * @param call
     * @param put
     */
    *queryDrawersList({ payload }, { call, put }) {
      const response = yield call(queryDrawersList, { ...payload });
      if (response.resultCode === 'ok') {
        yield put({
          type: 'refreshState',
          payload: {
            drawersList: response.content,
          },
        });
      } else {
        yield put({ type: 'refreshState', payload: { drawersList: [] } });
      }
    },

    // /**
    //  * 分页查询产品
    //  *
    //  * @param call
    //  * @param put
    //  * @param select
    //  */
    // *queryProducts({ payload }, { call, put, select }) {
    //   const response = yield call(queryProducts, { ...payload });
    //   if (response.resultCode === 'ok') {
    //     let content = response.content;
    //     yield put({
    //       type: 'refreshState',
    //       payload: {
    //         productList: response.content,
    //         productPage: R.isNil(content.page) ? Constants.DEFAULT_PAGE : content.page,
    //       },
    //     });
    //   } else {
    //     message.error(response.errMessage);
    //   }
    // },

    /**
     * 获取业务参数集合
     *
     * @param call
     * @param put
     * @param select
     */
    *getBusinessParamsByCode({ sprCode }, { call, put, select }) {
      const sessionSprCode = sessionStorage.getItem(Constants.PARAMPREFIX + sprCode);
      if (R.isNil(sessionSprCode)) {
        const response = yield call(getBusinessParamsByCode, { sprCode });
        if (response.resultCode === 'ok') {
          sessionStorage.setItem(Constants.PARAMPREFIX + sprCode, JSON.stringify(response.content));
          yield put({
            type: 'setBizParams',
            payload: {
              sprCode,
              list: response.content,
            },
          });
        }
      } else {
        yield put({ type: 'setBizParams', payload: { sprCode, list: JSON.parse(sessionSprCode) } });
      }
    },

    /**
     * 获取所有币种
     *
     * @param call
     * @param put
     */
    *getAllCurrencys({}, { call, put, select }) {
      const sessionCurrency = sessionStorage.getItem(Constants.preCurrency);
      if (R.isNil(sessionCurrency)) {
        const response = yield call(getAllCurrencys);
        if (response.resultCode === 'ok') {
          sessionStorage.setItem(Constants.preCurrency, JSON.stringify(response.content));
          yield put({ type: 'refreshState', payload: { currencys: response.content } });
        }
      } else {
        yield put({ type: 'refreshState', payload: { currencys: JSON.parse(sessionCurrency) } });
      }
    },

    /**
     * 获取所有口岸
     *
     * @param call
     * @param put
     */
    *getAllPorts({}, { call, put, select }) {
      const sessionPort = sessionStorage.getItem(Constants.PORTS);
      if (R.isNil(sessionPort)) {
        const response = yield call(getAllPorts, { status: '1' });
        if (response.resultCode === 'ok') {
          sessionStorage.setItem(Constants.PORTS, JSON.stringify(response.content));
          yield put({ type: 'refreshState', payload: { ports: response.content } });
        }
      } else {
        yield put({ type: 'refreshState', payload: { ports: JSON.parse(sessionPort) } });
      }
    },

    *add({ payload, callback }, { call, put }) {
      const response = yield call(addRule, payload);
      yield put({
        type: 'save',
        payload: response,
      });
      if (callback) callback();
    },
    *remove({ payload, callback }, { call, put }) {
      const response = yield call(removeRule, payload);
      yield put({
        type: 'save',
        payload: response,
      });
      if (callback) callback();
    },
    *update({ payload, callback }, { call, put }) {
      const response = yield call(updateRule, payload);
      yield put({
        type: 'save',
        payload: response,
      });
      if (callback) callback();
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        data: action.payload,
      };
    },
    /**
     * 设置业务参数
     *
     * @param state
     * @param payload
     */
    setBizParams(state, { payload }) {
      let newState = state.bizParams;
      if (payload.sprCode != undefined) {
        newState[payload.sprCode] = payload.list;
      }
      return { ...state, bizParams: newState };
    },

    /**
     * 刷新state
     *
     * @param state
     */
    refreshState(state, { payload }) {
      return { ...state, ...payload };
    },
  },
};

export default Model;
